package com.liyuan.yiqixing.controller;

import com.liyuan.yiqixing.model.Item;
import com.liyuan.yiqixing.model.Page;
import com.liyuan.yiqixing.model.ResultJson;
import com.liyuan.yiqixing.service.ItemService;
import com.liyuan.yiqixing.service.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class IndexController {
    @Value("${items.scale}")
    private int scale;
    @GetMapping({"/index"})
    public void index(HttpServletResponse response,
                      HttpServletRequest request) throws ServletException, IOException {
        request.getRequestDispatcher("/index.html").forward(request,response);
    }


    @Autowired
    ItemService itemService;
    @Autowired
    PageService pageService;
    @PostMapping("/items/{currentPage}")
    public ResultJson index(@PathVariable("currentPage")Integer currentPage){
        Item[] items=itemService.retrieveItems(currentPage, scale);
        Page page =pageService.paging(currentPage,scale,itemService.sum());
        return new ResultJson(200,"get items success!",new Object[]{items,page});
    }

    @GetMapping("/items/{id}")
    public void itemsId(HttpServletRequest request,
                        HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/item.html").forward(request,response);
    }
}
